package com.uniledger.exchange.stellar;

import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;

import com.orhanobut.logger.Logger;
import com.uniledger.exchange.BuildConfig;
import com.uniledger.exchange.UniApp;
import com.uniledger.exchange.login.Admin;
import com.uniledger.exchange.model.OkSingleton;

import org.stellar.sdk.Asset;
import org.stellar.sdk.AssetTypeCreditAlphaNum4;
import org.stellar.sdk.ChangeTrustOperation;
import org.stellar.sdk.KeyPair;
import org.stellar.sdk.Memo;
import org.stellar.sdk.Network;
import org.stellar.sdk.Server;
import org.stellar.sdk.Transaction;
import org.stellar.sdk.responses.AccountResponse;
import org.stellar.sdk.responses.SubmitTransactionResponse;

import java.io.IOException;

public class TrustIntentService extends IntentService {

    public static void start(Context context, Admin admin) {
        Intent intent = new Intent(TransactionUtils.ACTION_TRUST);
        intent.setPackage(context.getPackageName());
        intent.putExtra("Admin", admin);
        context.startService(intent);
    }

    public TrustIntentService() {
        super("TrustIntentService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Admin admin = intent.getParcelableExtra("Admin");
        trust(admin);
    }

    private void trust(Admin admin) {
        try {
            //TODO 信任资产发行方
            KeyPair source = OkSingleton.getInstance().getSourceKeyPair();
            KeyPair destination = KeyPair.fromAccountId(admin.issuingAccountId);

            //保存当前资产发行账户密钥对
            OkSingleton.getInstance().setIssuingKeyPair(destination);
            OkSingleton.getInstance().setBaseKeyPair(KeyPair.fromAccountId(admin.baseAccountId));

            Network.use(new Network("Standalone Network ; February 2017"));
            Server server = new Server(BuildConfig.STELLAR_HOST);
            server.accounts().account(destination);
            AccountResponse sourceAccount = server.accounts().account(source);

            Asset asset = new AssetTypeCreditAlphaNum4("AED", destination);
            String limit = "922337203685.4775807";

            ChangeTrustOperation operation = new ChangeTrustOperation.Builder(asset, limit)
                    .setSourceAccount(source)
                    .build();

            // Start building the transaction.
            Transaction transaction = new Transaction.Builder(sourceAccount)
                    .addOperation(operation)
                    // A memo allows you to add your own metadata to a transaction. It's
                    // optional and does not affect how Stellar treats the transaction.
                    .addMemo(Memo.text("Test Transaction"))
                    .build();
            // Sign the transaction to prove you are actually the person sending it.
            transaction.sign(source);

            SubmitTransactionResponse response = server.submitTransaction(transaction);
            Logger.d("Success!");
            Logger.d(response);
        } catch (IOException e) {
            Logger.d(e.getMessage());
            start(UniApp.getInstance(), admin);
        } catch (Exception e) {
            Logger.d("Something went wrong!");
            Logger.d(e.getMessage());
            // If the result is unknown (no response body, timeout etc.) we simply resubmit
            // already built transaction:
            // SubmitTransactionResponse response = server.submitTransaction(transaction);
            start(UniApp.getInstance(), admin);
        }
    }


}
